﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

using CMN.Common;
using CMN.Entity;
using CMN.BLL;
using CMN.Cache;
using System.IO;

namespace CMN.Extends.Job
{
    public class JobExecutor
    {
        /// <summary>
        /// 新政任务
        /// </summary>
        /// <param name="job"></param>
        /// <param name="interval">毫秒</param>
        /// <param name="executionState"></param>
        public JobExecutor(IJob job, int interval, object executionState)
        {
            this.Job = job;
            this.Interval = interval;
            this.ExecutionState = executionState;
        }
        public IJob Job { get; private set; }
        public int Interval { get; private set; }
        public object ExecutionState { get; private set; }
        public bool Started { get; set; }
        public bool IsRunning { get; private set; }
        private Timer timer;

        public void Start()
        {
            if (Started)
            {
                return;
            }
            timer = new Timer(new TimerCallback(TimerCallback), ExecutionState,Interval, Interval);
            Started = true;
            //AppLog.Write(string.Concat("任务：", Job.ToString(), "Start"), AppLog.LogMessageType.Debug);
        }
        private void TimerCallback(object state)
        {
           // Common.FileTxtLogs.WriteLog(string.Concat(DateTime.Now.ToShortDateString(), "TimerCallback执行生成静态"), false);
            if (!Started || IsRunning)
            {
                return;
            }
            
            timer.Change(Timeout.Infinite, Timeout.Infinite);

            try
            {
                //Common.FileTxtLogs.WriteLog(string.Concat(DateTime.Now.ToShortDateString(), "Execute执行生成静态"), false);
                Job.Execute(state);
            }
            catch (Exception e)
            {
                Job.Error(e);
            }

            IsRunning = false;

            if (Started)
            {
                timer.Change(Interval, Interval);
            }
        }

        public void Stop()
        {
            AppLog.Write(string.Concat("任务：", Job.ToString(), "Stop"), AppLog.LogMessageType.Debug);
            timer.Dispose();
            timer = null;
        }
    }
}

